﻿#Add-PSSnapIn Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
if ((Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null ) {
	Add-PSSnapin Microsoft.SharePoint.Powershell
}

$realm = Get-SPAuthenticationRealm

$certificatePath = "C:\Certificates\STS.cer"
$certificate = Get-PfxCertificate $certificatePath

$issuerId = "e1b853c1-4ea5-4647-a29c-aa335c5a28f1";
$issuerName = $issuerID + "@" + $realm
$secureTokenIssuer = New-SPTrustedSecurityTokenIssuer -Name $issuerId -RegisteredIssuerName $issuerName -Certificate $certificate -IsTrustBroker

$clientID = "3658bfda-062e-43cc-bea1-04b019d8c4ad";
$appIdentifier = $clientID + "@" + $realm
$appDisplayName = "MCSWebApp"

$webApps = Get-SPWebApplication
foreach ($webApp in $webApps) {
	foreach($site in $webApp.Sites) {
		$IsPublishingSite = [Microsoft.SharePoint.Publishing.PublishingSite]::IsPublishingSite($site)
		if($IsPublishingSite){
			$appPrincipal = Register-SPAppPrincipal -Site $site.RootWeb -NameIdentifier $appIdentifier -DisplayName $appDisplayName
			Set-SPAppPrincipalPermission -Site $site.RootWeb -AppPrincipal $appPrincipal -Scope SiteCollection -Right FullControl -EnableAppOnlyPolicy
		}
	}
}

$sts = Get-SPSecurityTokenServiceConfig
$sts.AllowOAuthOverHttp = $true
$sts.Update()